package com.alan.mvvm.utils;

import android.annotation.SuppressLint;
import android.content.Context;

import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;

import com.alan.base.utils.Logger;
import com.alan.mvvm.base.BaseViewModel;
import com.alan.mvvm.base.ConstrainBindingLayout;
import com.alan.mvvm.base.IBaseComponents;
import com.alan.mvvm.base.IViewBindingComponents;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Utils {

    @SuppressLint("DiscouragedApi")
    public static <VB extends ViewDataBinding> int getRes(Context context, IViewBindingComponents<VB> iBaseComponents) {
        Type type = iBaseComponents.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] arguments = ((ParameterizedType) type).getActualTypeArguments();
            if (arguments.length == 0) {
                return -1;
            }
            String binding = arguments[0].toString();
            Logger.d(binding);
            String name = binding.substring(binding.lastIndexOf(".") + 1);
            name = name.substring(0, name.lastIndexOf("Binding"));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < name.length(); i++) {
                char c = name.charAt(i);
                if (Character.isUpperCase(c) && i != 0) {
                    sb.append("_");
                }
                sb.append(Character.toLowerCase(c));
            }
            Logger.v(sb.toString());
            return context.getResources().getIdentifier(sb.toString(), "layout", context.getPackageName());
        }
        return -1;
    }

    public static <VB extends ViewDataBinding, VM extends BaseViewModel> VM initViewModel(ViewModelStoreOwner owner, IBaseComponents<VB, VM> iBaseComponents){
        Type type = iBaseComponents.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type actualTypeArgument = ((ParameterizedType) type).getActualTypeArguments()[1];
            Class<VM> tClass = (Class<VM>) actualTypeArgument;
            return new ViewModelProvider(owner).get(tClass);
        } else {
            return  (VM) new ViewModelProvider(owner).get(BaseViewModel.class);
        }
    }

}
